package com.news.view;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.xiang.news.R;
import com.news.activity.ContentDetailActivity;
import com.news.activity.MainActivity;
import com.news.contant.Contant;
import com.news.db.DBUtil;
import com.news.db.info.ContentInfo;
import com.rss.data.RssFeed;
import com.rss.data.RssItem;
import com.rss.sax.RssHandler;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class TittleListViewPagerAdapter extends PagerAdapter {
	Context context;
	List<String> urlList;
	LayoutInflater inflater;
	private RssFeed feed;

	myHandler handler;

	ProgressDialog progressDialog;

	Toast toast;

	DBUtil dbUtil;
	
	private final static byte[] _writeLock = new byte[0]; // 同步锁

	// private List<Map<String, Object>> tittle_List = new ArrayList<Map<String,
	// Object>>();

	public TittleListViewPagerAdapter(Context ctx, List<String> _list) {
		this.context = ctx;
		inflater = LayoutInflater.from(ctx);
		this.urlList = _list;
		handler = new myHandler();
	}

	@Override
	public int getCount() {
		return urlList.size();
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return arg0 == arg1;
	}

	@Override
	public Object instantiateItem(View container, int position) {
		View view = getView(position);
		((ViewPager) container).addView(view);
		return view;
	}

	@Override
	public void destroyItem(View container, int position, Object object) {
		((ViewPager) container).removeView((View) object);
	}

	private View getView(int position) {
		String urlStr = urlList.get(position);
		final String columnId = Contant.columnID[position];// 栏目id
		View view = inflater.inflate(R.layout.tittle_view_layout, null);
		final ViewHolder holder = new ViewHolder();
		holder.list = (ListView) view.findViewById(R.id.tittle_list);

//		showListview(holder.list, columnId);// 显示文章列表
		
		getDataFromDb(holder.list, columnId);
		
		refleshRss(columnId, urlStr, holder.list);

		return view;
	}

	class ViewHolder {
		ListView list;
	}

	private void refleshRss(final String columnId, String url,
			final ListView listview) {
		final String RssURL = url;
		// progressDialog = ProgressDialog.show(context, "正在加载",
		// " 正在努力为您获取文章列表……",
		// true, true);

		new Thread() {
			@Override
			public void run() {
				super.run();
				feed = getFeed(RssURL);
				Message msg = new Message();
				msg.what = Contant.GET_RSS_TIITLE_LIST_SUCCESS;

				Bundle bundle = new Bundle();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("feed", feed);
				map.put("listview", listview);
				map.put("columnid", columnId);
				msg.obj = map;

				handler.sendMessage(msg);
			}
		}.start();
	}

	private RssFeed getFeed(String urlString) {
		try {
			URL url = new URL(urlString);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			XMLReader xmlReader = parser.getXMLReader();

			RssHandler rssHandler = new RssHandler();
			xmlReader.setContentHandler(rssHandler);

			InputStream in = new BufferedInputStream(url.openStream());
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");

			xmlReader.parse(new InputSource(isr));

			return rssHandler.getFeed();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	class myHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			if (msg.what == Contant.GET_RSS_TIITLE_LIST_SUCCESS) {

				Map<String, Object> map = (Map<String, Object>) msg.obj;
				final ListView listview = (ListView) map.get("listview");
				final String columnId = (String) map.get("columnid");
				final RssFeed feed = (RssFeed) map.get("feed");

				if (feed == null) {
					toastShow("没有拿到新闻列表哦，请查查您的网络吧");
					return;
				}
				final List<Map<String, Object>> tittle_List = feed
						.getAllItemsForListView();

				insertToDatabase(tittle_List, columnId);// 插入文章列表
//				showListview(listview, columnId);// 显示文章列表
				
				
				getDataFromDb(listview, columnId);
					

			}
			if (msg.what == Contant.GET_RSS_TIITLE_LIST_FROM_DB_SUCCESS) {
				Map<String, Object> map = (Map<String, Object>) msg.obj;
				final ListView listview = (ListView) map.get("listview");
				final List<Map<String, Object>> tittle_List = (List<Map<String, Object>>) map.get("tittle_List");
				
				showListview(listview, tittle_List);
			}
		}
	}
	
	/**
	 * 用线程来查询数据库（没完成）
	 * @param listview
	 * @param columnId
	 */
	private void getDataFromDb(final ListView listview, final String columnId) {
		new Thread(){
			@Override
			public void run() {
				super.run();
				final List<Map<String, Object>> tittle_List = getTitleFromDB(columnId);// 根据栏目ID获取文章列表
				Message msg = new Message();
				msg.what = Contant.GET_RSS_TIITLE_LIST_FROM_DB_SUCCESS;

				Bundle bundle = new Bundle();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("tittle_List", tittle_List);
				map.put("listview", listview);
				msg.obj = map;

				handler.sendMessage(msg);
			}
		}.start();
		
	}
	
	/**
	 * 显示文章列表
	 * 
	 * @param listview
	 * @param tittle_List
	 */
	private void showListview(ListView listview, final List<Map<String, Object>> tittle_List) {

//		final List<Map<String, Object>> tittle_List = getTitleFromDB(columnId);// 根据栏目ID获取文章列表
		int size = tittle_List.size();
		System.out.println("list size from db: " + size);
		if (size < 0) {
			return;
		}

		final TittleListAdapter adapter = new TittleListAdapter(context,
				tittle_List);

		listview.setAdapter(adapter);
		listview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(context, ContentDetailActivity.class);
				Bundle bundle = new Bundle();

				bundle.putString(RssItem.TITLE, (String) tittle_List.get(arg2)
						.get(RssItem.TITLE));
				// bundle.putString(RssItem.TITLE,
				// feed.getItem(arg2).getTitle());
				bundle.putString(RssItem.LINK, (String) tittle_List.get(arg2)
						.get(RssItem.LINK));
				
				bundle.putString(ContentInfo.CONTENT, (String) tittle_List.get(arg2)
						.get(ContentInfo.CONTENT));

				// bundle.putString(RssItem.LINK, feed.getItem(arg2).getLink());
				bundle.putString(RssItem.PUBDATE, (String) tittle_List
						.get(arg2).get(RssItem.PUBDATE));
				bundle.putString("startTag", Contant.STARTTAG);
				bundle.putString("endTag", Contant.ENDTTAG);

				intent.putExtra("RssFeed", bundle);
				context.startActivity(intent);
				((Activity) context).overridePendingTransition(R.anim.right_in,
						R.anim.left_out);

				setContentIsRead((String) tittle_List.get(arg2).get(
						RssItem.LINK));// 插入已读标记

				tittle_List.get(arg2).put(
						ContentInfo.CONTENTREAD, "1");
				adapter.resetData(tittle_List);
				adapter.notifyDataSetChanged();
			}
		});

	}


//	/**
//	 * 显示文章列表
//	 * 
//	 * @param listview
//	 * @param tittle_List
//	 */
//	private void showListview(ListView listview, String columnId) {
//
//		final List<Map<String, Object>> tittle_List = getTitleFromDB(columnId);// 根据栏目ID获取文章列表
//		int size = tittle_List.size();
//		System.out.println("list size from db: " + size);
//		if (size < 0) {
//			return;
//		}
//
//		final TittleListAdapter adapter = new TittleListAdapter(context,
//				tittle_List);
//
//		listview.setAdapter(adapter);
//		listview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
//		listview.setOnItemClickListener(new OnItemClickListener() {
//			@Override
//			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//					long arg3) {
//				Intent intent = new Intent(context, ContentDetailActivity.class);
//				Bundle bundle = new Bundle();
//
//				bundle.putString(RssItem.TITLE, (String) tittle_List.get(arg2)
//						.get(RssItem.TITLE));
//				// bundle.putString(RssItem.TITLE,
//				// feed.getItem(arg2).getTitle());
//				bundle.putString(RssItem.LINK, (String) tittle_List.get(arg2)
//						.get(RssItem.LINK));
//
//				// bundle.putString(RssItem.LINK, feed.getItem(arg2).getLink());
//				bundle.putString(RssItem.PUBDATE, (String) tittle_List
//						.get(arg2).get(RssItem.PUBDATE));
//				bundle.putString("startTag", Contant.STARTTAG);
//				bundle.putString("endTag", Contant.ENDTTAG);
//
//				intent.putExtra("RssFeed", bundle);
//				context.startActivity(intent);
//				((Activity) context).overridePendingTransition(R.anim.right_in,
//						R.anim.left_out);
//
//				setContentIsRead((String) tittle_List.get(arg2).get(
//						RssItem.LINK));// 插入已读标记
//
//				tittle_List.get(arg2).put(
//						ContentInfo.CONTENTREAD, "1");
//				adapter.resetData(tittle_List);
//				adapter.notifyDataSetChanged();
//			}
//		});
//
//	}

	private void toastShow(String str) {
		if (toast == null) {
			toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
		} else {
			// toast.cancel();
			toast.setText(str);
		}
		toast.show();
	}

	/**
	 * 向数据库插入文章列表
	 * 
	 * @param list
	 * @param columnId
	 */
	private void insertToDatabase(List<Map<String, Object>> list,
			String columnId) {
		synchronized (_writeLock) {
		if (dbUtil == null) {
			dbUtil = new DBUtil(context);
		}
		dbUtil.insertTittleList(list, columnId);
		}
	}

	/**
	 * 向数据库更新已读标记
	 */
	private void setContentIsRead(String url) {
		synchronized (_writeLock) {
		if (dbUtil == null) {
			dbUtil = new DBUtil(context);
		}
		dbUtil.setContentIsRead(url);
		}
	}

	/**
	 * 根据栏目ID获取文章列表
	 * 
	 * @return
	 */
	public List<Map<String, Object>> getTitleFromDB(String columnid) {
		synchronized (_writeLock) {
		if (dbUtil == null) {
			dbUtil = new DBUtil(context);
		}
		return dbUtil.getTitleFromDB(columnid);
	}
	}
}
